package {
	import ypmits.setup.EasySetup;
	import ypmits.setup.EasySetupInput;
	import ypmits.setup.view.FullScreenButtonGraphic;

	import com.greensock.TweenLite;
	import com.greensock.easing.Back;

	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.ColorTransform;
	import flash.net.URLRequest;
	import flash.text.TextField;

	/**
	 * @author Dave Lenz
	 */
	public class Rotate3DTest extends Sprite {

		private static const ONE_PERCENT : Number = .0111111111;
		
		private var picture : Sprite;
		private var tf : TextField;
		private var bitmap : Bitmap;
		private var plus : Boolean = false;
		private var c : Number;

		
		public function Rotate3DTest() {
			var _i : EasySetupInput = new EasySetupInput( );
			_i.fullscreenbuttongraphic = new FullScreenButtonGraphic( 15, 15, 0xFFFFFF, stage );
			
			EasySetup.instance.init( this, _i );
			
			draw( );
		}

		
		private function draw() : void {
			picture = new Sprite( );
			picture.x = 400;
			picture.y = 400;
			addChild( picture );
			
			tf = new TextField();
			tf.textColor = 0x000000;
			tf.x = 200;
			addChild( tf );
			
			loadPicture( "stuff/george.png" );
		}

		
		private function loadPicture( url : String ) : void {
			var l : Loader = new Loader( );
			l.contentLoaderInfo.addEventListener( Event.COMPLETE, completeHandler );
			l.load( new URLRequest( url ) );
		}

		
		private function completeHandler( e : Event ) : void {
			bitmap = Bitmap( LoaderInfo( e.currentTarget ).content );
			bitmap.x = -( bitmap.width * .5);
			bitmap.y = -( bitmap.height * .5);
			bitmap.smoothing = true;
			picture.addChild( bitmap );
			
			picture.addEventListener( MouseEvent.CLICK, rotate );
		}
		
		
		private function rotate( e : MouseEvent ) : void {
			plus ? rotateMinus() : rotatePlus();
		}
		
		
		private function rotatePlus( ) : void {
			plus = true;
			TweenLite.to( picture, 1, {rotationY:180, ease:Back.easeOut, onUpdate:enterHandler, onComplete:rotationDone} );
		}
		
		
		private function rotateMinus( ) : void {
			plus = false;
			TweenLite.to( picture, 1, {rotationY:0, ease:Back.easeOut, onUpdate:enterHandler, onComplete:rotationDone} );
		}

		
		private function rotationDone() : void {
			picture.transform.matrix = null;
		}

		
		private function enterHandler( ) : void {
			var r : Number = Math.abs( picture.rotationY );
			r >= 360 ? r = 0 : null;
			tf.text = String( r );
			if( ( r >= 0 ) && ( r <= 90 ) ) {
				c = 1 - Math.abs( ONE_PERCENT * r );
			} else if ( ( r > 90 ) && ( r <= 180 ) ) {
				c = 1 - Math.abs( ( 180 - r ) * ONE_PERCENT );
			} else if ( ( r > 180 ) && ( r <= 270 ) ) {
				c = Math.abs( ( r - 270 ) * ONE_PERCENT );
			} else if ( ( r > 270 ) && ( r <= 360 ) ) {
				c = 1 - Math.abs( ( r - 360 ) * ONE_PERCENT );
			}
			bitmap.transform.colorTransform = new ColorTransform( c, c, c, 1, 0, 0, 0, 0 );
		}
	}
}
